package com.qidian.buy.order.service.impl;

import com.qidian.buy.order.entity.Logistics;
import com.qidian.buy.order.entity.Order;
import com.qidian.buy.order.entity.Orderitem;
import com.qidian.buy.order.mapper.LogisticsMapper;
import com.qidian.buy.order.mapper.OrderMapper;
import com.qidian.buy.order.mapper.OrderitemMapper;
import com.qidian.buy.order.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.order.vo.OrderVO;
import com.qidian.buy.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2024-05-21
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderitemMapper orderitemMapper;
    @Autowired
    private LogisticsMapper logisticsMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    @Transactional
    public QdResult saveOrder(OrderVO vo) {
        // 生成订单编号// 订单编号我们通过redis生成
        // 唯一，速度快，可读性强  一般订单编号就像身份证号码一样分段表示各种不同的意义
        // 我们在这里把前面的6位直接固定，后面在生成9位表示订单序列，这个序列从redis中获取
        StringBuilder sb = new StringBuilder("952278");
        String key = "ORDER_SEQ";
        if(!stringRedisTemplate.hasKey(key)){
            String seq = "000000001";
            stringRedisTemplate.opsForValue().set(key,"1");
            sb.append(seq);
        }else{
            // 获取对应的序列
            Long increment = stringRedisTemplate.opsForValue().increment(key);
            // 将increment修改长度为9的序列
            for (int i = 0; i < 9 - increment.toString().length(); i++){
                sb.append("0");
            }
            // 最终将increment加入到sb中
            sb.append(increment);
        }
        // 添加订单
        vo.setOrderId(sb.toString());
        int insert = orderMapper.insert(vo);
        if(insert == 1) {
            // 添加物流信息
            Logistics logistics = vo.getLogistics();
            logistics.setOrderId(vo.getOrderId());
            logisticsMapper.insert(logistics);
            // 添加订单明细
            List<Orderitem> orderitems = vo.getOrderitems();
            for (Orderitem orderitem : orderitems){
                orderitem.setOrderId(sb.toString());
                orderitemMapper.insert(orderitem);
            }
            // 发送消息到MQ
            return QdResult.success();
        }
        return QdResult.error("添加订单失败");
    }
}
